package thread.pool;

import java.util.concurrent.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Random;

public class ThreadPoolPracticalExample {

    public static void main(String[] args) {
        // 模拟实际应用场景
        practicalExample();
    }

    public static void practicalExample() {
        System.out.println("=== 线程池实际应用场景示例 ===");

        // 创建一个适合处理并发任务的线程池
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                4,                          // 核心线程数
                8,                          // 最大线程数
                60L,                        // 空闲线程存活时间
                TimeUnit.SECONDS,           // 时间单位
                new ArrayBlockingQueue<>(10), // 有界队列
                new ThreadFactory() {
                    private int counter = 0;
                    @Override
                    public Thread newThread(Runnable r) {
                        return new Thread(r, "BusinessThread-" + (++counter));
                    }
                },                          // 自定义线程工厂
                new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略
        );

        // 模拟处理用户订单
        List<Future<String>> futures = new ArrayList<>();
        Random random = new Random();

        for (int i = 1; i <= 10; i++) {
            final int orderId = i;
            final int processingTime = random.nextInt(3000) + 1000; // 1-4秒处理时间

            Future<String> future = executor.submit(() -> {
                String threadName = Thread.currentThread().getName();
                System.out.println("订单 " + orderId + " 开始处理，预计耗时 " + processingTime + "ms，处理线程: " + threadName);

                // 模拟处理订单
                try {
                    Thread.sleep(processingTime);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    return "订单 " + orderId + " 处理被中断";
                }

                // 模拟处理结果
                boolean success = random.nextDouble() > 0.1; // 90%成功率
                if (success) {
                    return "订单 " + orderId + " 处理成功，耗时 " + processingTime + "ms";
                } else {
                    return "订单 " + orderId + " 处理失败";
                }
            });

            futures.add(future);
        }

        // 收集处理结果
        for (int i = 0; i < futures.size(); i++) {
            try {
                String result = futures.get(i).get(5, TimeUnit.SECONDS);
                System.out.println("处理结果: " + result);
            } catch (Exception e) {
                System.out.println("获取订单 " + (i+1) + " 处理结果时发生异常: " + e.getMessage());
            }
        }

        // 关闭线程池
        executor.shutdown();
        try {
            if (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
                System.out.println("线程池未能正常关闭，强制关闭");
                executor.shutdownNow();
            }
        } catch (InterruptedException e) {
            executor.shutdownNow();
        }

        // 输出最终统计信息
        System.out.println("\n最终统计:");
        System.out.println("核心线程数: " + executor.getCorePoolSize());
        System.out.println("最大线程数: " + executor.getMaximumPoolSize());
        System.out.println("已完成任务数: " + executor.getCompletedTaskCount());
        System.out.println("总任务数: " + executor.getTaskCount());
        System.out.println("活动线程数: " + executor.getActiveCount());
    }
}
